/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.factorial;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * Receives a sequence of integers from a {@link FactorialClient} to calculate
 * the factorial of the specified integer.
 *
 * 阶乘服务 , 服务端
 */
public final class FactorialServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    //服务端 端口: 8322
    static final int PORT = Integer.parseInt(System.getProperty("port", "8322"));

    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            //如果启用了ssl  , 那么初始化ssl上下文
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // boss 组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // worker 组
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //服务端启动类
            ServerBootstrap b = new ServerBootstrap();
            // 配置eventLoop
            b.group(bossGroup, workerGroup)
            //使用的channel  NioServerSocketChannel
             .channel(NioServerSocketChannel.class)
            //配置channel / pipline / handler
             .childHandler(new FactorialServerInitializer(sslCtx));

            //将服务绑定到端口上 ,阻塞 .
            //等待结束通知
            b.bind(PORT).sync().channel().closeFuture().sync();
        } finally {
            //关闭 boss group
            bossGroup.shutdownGracefully();
            // 关闭 worker group
            workerGroup.shutdownGracefully();
        }
    }
}
